<template>
    <div>
        <el-form
            ref="cultureScheme"
            :model="cultureScheme"
            :rules="cultureSchemeRules"
            label-width="96px"
            class="bg-white"
            label-position="right"
        >
            <el-row :gutter="10">
                <el-col :span="6">
                    <el-form-item :label="$t('culture.scheme.name') +':'">
                        <el-input
                            v-model="cultureScheme.name"
                            type="text"
                            style="width:100%"
                            :disabled="isDraft"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('culture.scheme.nameEn') +':'">
                        <el-input
                            v-model="cultureScheme.nameEn"
                            type="text"
                            style="width:100%"
                            :disabled="isDraft"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('culture.scheme.grade') +':'">
                        <el-input
                            v-model="cultureScheme.grade"
                            type="text"
                            style="width:100%"
                            :disabled="isDraft"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('culture.scheme.degreeType') +':'">
                    <el-select
                      v-model="cultureScheme.degreeType"
                      style="width:100%" :disabled="isDraft"
                      @change="initMajorData">
                      <el-option
                        v-for="item in options.degreeType"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('culture.scheme.faculty') +':'">
                        <el-select v-model="cultureScheme.faculty" style="width:100%" :disabled="isDraft"
                        @change="initMajorData">
                            <el-option
                                v-for="item in options.faculty"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('culture.scheme.major') +':'">
                        <el-select v-model="cultureScheme.majorI18n" style="width:100%" :disabled="isDraft">
                            <el-option
                                v-for="item in options.major"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('culture.scheme.trainingLevel') +':'">
                        <el-select
                            v-model="cultureScheme.trainingLevel"
                            style="width:100%"
                            :disabled="isDraft"
                        >
                            <el-option
                                v-for="item in options.trainingLevel"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('culture.scheme.trainingCategory') +':'" style="height:34px">
                        <el-select
                            v-model="cultureScheme.trainingCategory"
                            style="width:100%"
                            :disabled="isDraft"
                            multiple collapse-tags
                        >
                            <el-option
                                v-for="item in options.trainingCategory"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('culture.scheme.formLearning') +':'">
                        <el-select v-model="cultureScheme.formLearning" style="width:100%" :disabled="isDraft">
                            <el-option
                                v-for="item in options.formLearning"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="6">
          <el-form-item :label="$t('culture.scheme.spcialPlan') +':'">
            <el-select
              v-model="cultureScheme.spcialPlan"
              style="width:100%"
              disabled>
              <el-option
                v-for="item in options.spcialPlan"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
                </el-col>-->
                <!-- <el-col :span="6">
          <el-form-item :label="$t('culture.scheme.studentAbroad') +':'">
            <el-select
              v-model="cultureScheme.studentAbroad"
              style="width:100%"
              disabled>
              <el-option
                label="…"
                value="2"/>
              <el-option
                label="是"
                value="0"/>
              <el-option
                label="否"
                value="1"/>
            </el-select>
          </el-form-item>
                </el-col>-->
                <!-- <el-col :span="6">
          <el-form-item
            :label="$t('culture.scheme.lengthSchooling') +':'"
            prop="lengthSchooling">
            <el-input-number
              v-model="cultureScheme.lengthSchooling"
              :precision="1"
              :step="0.5"
              :max="10"
              style="width:100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            :label="$t('culture.scheme.maxLengthSchooling') +':'"
            prop="maxLengthSchooling">
            <el-input-number
              v-model="cultureScheme.maxLengthSchooling"
              :precision="1"
              :step="0.5"
              :max="10"
              style="width:100%"/>
          </el-form-item>
                </el-col>-->
                <!-- <el-col :span="6">
                    <el-form-item
                        :label="$t('culture.scheme.persionInCharge') +':'"
                        prop="persionInCharge"
                    >
                        <el-input
                            v-model="cultureScheme.persionInCharge"
                            type="text"
                            style="width:100%"
                        />
                    </el-form-item>
                </el-col>-->
                <el-col :span="6">
                    <el-form-item
                        :label="$t('culture.scheme.persionInCharge') +':'"
                        prop="approver"
                    >
                        <el-select
                            v-model="cultureScheme.approver"
                            :remote-method="remoteMethod"
                            filterable
                            remote
                            reserve-keyword
                            placeholder="账号或用户名"
                            style="width:100%"
                            :disabled="isRead"
                        >
                            <el-option
                                v-for="item in options.approver"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                                <span style="float: left">{{ item.label }}</span>
                                <span
                                    style="float: right; color: #8492a6; font-size: 13px"
                                >{{ item.value }}</span>
                            </el-option>
                        </el-select>
                        <template>
                            <div class="input-tips">
                                <span><i class="el-icon-warning"></i>  (学科专业委员会主任)</span>
                            </div>
                        </template>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('culture.scheme.entry') +':'">
                        <el-input :disabled="isRead" v-model="cultureScheme.entry" type="text" style="width:100%"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('culture.scheme.remark') +':'">
                        <el-input :disabled="isRead" v-model="cultureScheme.remark" type="text" style="width:100%"/>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-row class="pd-12px float-right" style="padding-right: 0;">
            <el-col :span="24">
                <el-button size="medium" @click="back">{{ $t('culture.scheme.back') }}</el-button>
                <el-button v-if="isRead || isDraft"
                    size="medium"
                    @click="submit('cultureScheme')"
                >{{ $t('culture.scheme.save') }}</el-button>
                <el-button
                    size="medium"
                    type="primary"
                    @click="nextStep"
                >{{ $t('culture.scheme.next') }}</el-button>
            </el-col>
        </el-row>
        <el-dialog :visible.sync="showDeleteDialog" title="删除章节" width="350px" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <el-row>
                <el-col style="text-align:center">您是否确认删除？</el-col>
            </el-row>
            <el-row>
                <el-col>
                    <div style="float:right;margin-top:25px">
                        <el-button size="mini" @click="cancelDelete">取消</el-button>
                        <el-button type="primary" size="mini" @click="confirmDelete">确认</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-dialog>

        <vue-html5-editor :content="content" :height="500"/>
    </div>
</template>
<script>
import * as API from "common/src/api/culture/cultruescheme";
import { findTeacherInfoList } from "common/src/api/studentinfo";
import UTILS from "common/src/utils/utils";
import { queryDic } from "common/src/api/dictionary";
import { findFaculty } from "common/src/api/faculty";
import { mapActions } from "vuex";
import { getGraduateDegreePage } from "common/src/api/resource/course";
const ROW_TYPE = {
    NORMAL: "normal",
    NEW: "new"
};

export default {
    name: "scheme-base-info",
    props: {
        next: {
            type: Function,
            default: null
        },
        schemeId: {
            type: String,
            default: null
        },
        isDraft: {
            type: Boolean,
            default: true
        },
        isRead: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            loading: false,
            cultureScheme: {
                trainingCategory:[],
            },
            cultureSchemeRules: {
                lengthSchooling: [
                    {
                        required: true,
                        message: "请输入方案名称",
                        trigger: "blur"
                    }
                ],
                maxLengthSchooling: [
                    {
                        required: true,
                        message: "请选择培养模板",
                        trigger: "blur"
                    }
                ],
                persionInCharge: [
                    {
                        min: 3,
                        max: 256,
                        message: this.$t("culture.scheme.stringlengthtip"),
                        trigger: "blur"
                    }
                ],
                entry: [
                    {
                        min: 3,
                        max: 256,
                        message: this.$t("culture.scheme.stringlengthtip"),
                        trigger: "blur"
                    }
                ],
                remark: [
                    {
                        min: 3,
                        max: 256,
                        message: this.$t("culture.scheme.stringlengthtip"),
                        trigger: "blur"
                    }
                ],
                approver: [
                    {
                        min: 3,
                        max: 256,
                        message: this.$t("culture.scheme.stringlengthtip"),
                        trigger: "blur"
                    }
                ]
            },
            // 下拉相关选项数据
            options: {
                grade: [],
                trainingLevel: [],
                faculty: [],
                major: [],
                degreeType: [],  // 学位类型
                spcialPlan: [],
                formLearning: [],
                studentAbroad: [],
                status: [],
                templateName: [],
                degreeCategory: [], // 学位类别
                trainingCategory: [], // 培养类别
                approver: []
            },
            showDeleteDialog: false,
            chapters: [],
            selectChapterId: 0,
            currentDeleteId: 0,
            editorText: ""
        };
    },
    created() {
        this.init();
        this.loading = false;
    },
    methods: {
        ...mapActions(["delTab"]),
        onContentChange(val) {
            this.editorText = val;
        },
        onContentChange2(val) {
            this.editorText2 = val;
        },
        afterChange() {},
        init() {
            this.loading = true;
            // 绑定培养层次
            this.initOptions();
            this.getSchemeInfo(this.schemeId);
        },
        initOptions() {
            findFaculty().then(res => { 
                let data = {"X_YX": res.data};
                UTILS.fillSelect({ faculty: "X_YX" }, data, this.options);
            });
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: [
                    "X_PYCC",
                    "K_XXXS",
                    "X_ZXJH",
                    "X_PYLB",
                    "X_XWLB",
                    "X_XWLX"
                ]
            };
            queryDic(data)
                .then(res => {
                    if (res.code === 200) {
                        // this.fillSelect(res.data);
                        UTILS.fillSelect(
                            {
                                trainingLevel: "X_PYCC",
                                degreeCategory: "X_XWLB",
                                spcialPlan: "X_ZXJH",
                                formLearning: "K_XXXS",
                                degreeType: "X_XWLX",
                                trainingCategory: "X_PYLB"
                            },
                            res.data,
                            this.options
                        );
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        // 获取模板信息
        getSchemeInfo(id) {
            if (!id) return;
            const params = {
                id: id
            };
            API.findCultureSchemeById(params).then(res => {
                if (res && res.code === 200) {
                    this.cultureScheme = res.data;
                    this.cultureScheme.trainingCategory = res.data.trainingCategory ? res.data.trainingCategory.split(",") : [];
                    // this.cultureScheme.entry =
                    //     this.$store.state.session.uid ||
                    //     localStorage.getItem("uid") ||
                    //     "";
                    this.cultureScheme.entry = res.data.entry;
                    //this.cultureScheme.approver = res.data.approver;
                    this.cultureScheme.remark = res.data.remark;
                    if(res.data.approver){
                        this.remoteMethod(res.data.approver);
                    }
                    this.__initMajor(this.cultureScheme.faculty)
                    // this.$set(this.options.approver, 0, {
                    //     name: this.cultureScheme.persionInCharge,
                    //     code: this.cultureScheme.approver
                    // });
                }
            });
        },
        // 新增
        addRow(row) {
            if (row.name.trim() === "") {
                this.$message({
                    type: "info",
                    message: "请填写模板名称"
                });
                return;
            }

            const maxObject = _.maxBy(this.chapters, c => c.id);
            if (isNaN(parseInt(maxObject.id))) {
                row.id = 1;
            } else {
                row.id = parseInt(maxObject.id) + 1;
            }
            row.opr = ROW_TYPE.NORMAL;
            this.appendCreateRow();
        },
        editRow(row) {
            this.selectChapterId = row.id;
        },
        removeRow(row) {
            this.showDeleteDialog = true;
            this.currentDeleteId = row.id;
        },
        saveRow(row) {
            this.selectChapterId = 0;
        },
        cancelRow(row) {
            this.selectChapterId = 0;
        },
        // 添加新增行
        appendCreateRow() {
            this.chapters.push({
                id: "",
                name: "",
                nameEn: "",
                contentLength: "",
                contentMethod: "",
                opr: ROW_TYPE.NEW
            });
        },
        // 删除当前行，重新设置序号,排除新增行
        confirmDelete() {
            this.showDeleteDialog = false;
            const newChapters = _.cloneDeep(this.chapters);
            _.remove(newChapters, c => c.id == this.currentDeleteId);
            newChapters.forEach((c, index) => {
                if (c.id) {
                    c.id = parseInt(index) + 1;
                }
            });
            this.chapters = newChapters;
        },
        cancelDelete() {
            this.showDeleteDialog = false;
        },
        // 返回
        back() {
            this.delTab("/cultureSchemeDetail");
            this.$router.push({path: `/cultureSchemeManage`});
        },
        isValid() {
            let result = true;
            let msg = "";
            if (this.queryForm.templateName.trim() === "") {
                result = false;
                msg = "请填写模板名称";
            } else if (this.queryForm.year === "") {
                result = false;
                msg = "请选择年级";
            } else if (this.queryForm.trainingLevel === "") {
                result = false;
                msg = "请选择培养层次";
            }
            if (!result) {
                this.$message({
                    type: "info",
                    message: msg
                });
            }
            return result;
        },
        // 保存
        submit(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if(this.cultureScheme.approver){
                        this.cultureScheme.persionInCharge = this.options.approver.find(
                            item => item.value === this.cultureScheme.approver
                        ).label;
                    }
                    API.updateCultureScheme(this.cultureScheme).then(res => {
                        if (res && res.code === 200) {
                            this.$notify.success({
                                title: this.$t("culture.scheme.success"),
                                message: this.$t("culture.scheme.savesuccess")
                            });
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        // 下一步
        nextStep() {
            if (this.next) {
                this.next(2);
            }
        },
        remoteMethod(query) {
            if (query !== "") {
                setTimeout(() => {
                    API.findSubjectMajorRole({
                        condition: query
                    }).then(res => {
                        console.log(res)
                        if (res && res.code === 200) {
                            if(res.data.length > 0){
                                this.options.approver = res.data.map(item => ({
                                                        label: item.userName,
                                                        value: item.userCode
                                                    }));
                                console.log(this.options.approver)
                                if(res.data.length == 1){
                                    this.cultureScheme.approver = res.data[0].userCode;
                                }
                            }
                        }
                    });
                }, 200);
            } else {
                this.options.approver = [];
            }
        },
        initMajorData() {
            if (this.cultureScheme.faculty) {
               this.cultureScheme.major = "";
               this.cultureScheme.majorI18n = "";
               this.__initMajor(this.cultureScheme.faculty)
            }
        },
        __initMajor(collegeVal) {
            if (collegeVal) {
                this.options["major"] = [];
                const data = {
                    college: collegeVal,
                    page: false,
                    type: this.cultureScheme.degreeType
                };
                getGraduateDegreePage(data).then(res => {
                    if (res.code === 200) {
                        let majors = _.map(res.data.list, item => {
                            return {
                                value: item.code,
                                majorId: item.majorId,
                                // label:
                                //     "cn" !== this.$store.getters.language
                                //         ? item.majorNameEn
                                //         : item.majorName
                                label:
                                    "cn" !== this.$store.getters.language
                                        ? item.nameEn
                                        : item.name
                            };  
                        });
                        majors &&
                            0 < majors.length &&
                            (this.options["major"] = [...majors]);
                    }
                });
            }
        }
    }
};
</script>
<style lang="scss" scoped>
.base-title {
    border-bottom: 1px solid #cccccc;
    line-height: 30px;
    margin-bottom: 20px;
}
.input-tips{
    position: absolute;
    left: -20px;
    top: 34px;
    color:rgba(136, 150, 167, 0.847059);
}
</style>
